package com.zx.idc.backend.gui.sys;

import com.zx.idc.backend.gui.common.BaseApi;
import com.zx.idc.backend.gui.common.Result;
import com.zx.idc.common.util.StreamUtils;
import com.zx.idc.ds.sys.entity.NetworkManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author rxliuli
 */
@RestController
@RequestMapping("/api/network-manager")
public class NetworkManagerController extends BaseApi {
    /**
     * 获取当前应用的网络信息列表
     */
    @GetMapping("/list-for-all")
    public Result<List<NetworkManager>> listForAll() {
        try {
            final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            final List<NetworkInterface> ins = new LinkedList<>();
            while (en.hasMoreElements()) {
                ins.add(en.nextElement());
            }
            final Function<NetworkInterface, NetworkManager> ni2nmMap = in -> {
                try {
                    InterfaceAddress interfaceAddress = null;
                    for (InterfaceAddress interfaceAddressEntity : in.getInterfaceAddresses()) {
                        if (!interfaceAddressEntity.getAddress().getHostName().contains(":")) {
                            interfaceAddress = interfaceAddressEntity;
                            break;
                        }
                    }
                    return new NetworkManager(
                        in.getName(),
                        null,
                        in.isUp() ? 1 : 2,
                        interfaceAddress == null ? null : interfaceAddress.getAddress().getHostAddress(),
                        interfaceAddress == null ? null : displayPrefix(interfaceAddress.getNetworkPrefixLength()),
                        getDefaultAddress()
                    );
                } catch (SocketException e) {
                    throw new RuntimeException(e);
                }
            };
            return success(ins.stream()
                .map(ni2nmMap)
                .collect(Collectors.toList()));
        } catch (SocketException e) {
            return success(null);
        }
    }

    private String getDefaultAddress() {
        String defaultAddress = "";
        BufferedReader output = null;
        try {
            Process result = Runtime.getRuntime().exec("netstat -rn");

            output = new BufferedReader(new InputStreamReader(
                result.getInputStream()));


            String line = output.readLine();
            while (line != null) {
                if (line.contains("0.0.0.0")) {

                    StringTokenizer stringTokenizer = new StringTokenizer(line);
                    stringTokenizer.nextElement(); // first element is 0.0.0.0
                    stringTokenizer.nextElement(); // second element is 0.0.0.0
                    defaultAddress = (String) stringTokenizer.nextElement();
                    break;
                }

                line = output.readLine();

            } // while
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("", e);
        } finally {
            StreamUtils.closeStream(output);
        }

        return defaultAddress;

    }

    // 将代表  MAC 地址的字节数组装换为 16 进制数
    public String displayMac(byte[] mac) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            byte b = mac[i];
            int value = 0;
            if (b > 0) {
                value = b;
            } else {
                value = 256 + b;
            }
            str.append(Integer.toHexString(value));
            if (i != mac.length - 1) {
                str.append(" - ");
            }
        }
        return str.toString();
    }

    // 转换子网掩码
    public String displayPrefix(int mask) {
        StringBuilder maskStr = new StringBuilder();
        int[] maskIp = new int[4];
        for (int i = 0; i < maskIp.length; i++) {
            maskIp[i] = (mask >= 8) ? 255 : (mask > 0 ? (mask & 0xff) : 0);
            mask -= 8;
            maskStr.append(maskIp[i]);
            if (i < maskIp.length - 1) {
                maskStr.append(".");
            }
        }
        return maskStr.toString();
    }
}
